package org.example.controller;

import org.example.annotations.ProcessInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("*")
@CrossOrigin("*")
public class UploadFileController {

    @Value("${imageLocaltion}")
    private String fileLocation;

    @Value("${imageServer}")
    private String imageServer;

    @PostMapping("/upload")
    @ProcessInfo("文件上传")
    public String uploadFile(MultipartFile[] images, MultipartFile other,String description, Map<String,Object> map){
        List<String> imagesFilename = new ArrayList<>();
        //多个文件
        for (MultipartFile image:images) {
            String encapsulation = encapsulation(image);
            imagesFilename.add(imageServer+encapsulation);
        }

        //单个文件
        String encapsulation = encapsulation(other);

        map.put("images",imagesFilename);
        map.put("other",imageServer+encapsulation);

        return "other_success";

    }

    //方法封装
    public String encapsulation(MultipartFile file){
        //获取文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件名  file.png --> png
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //创建新的文件名
        String newFile = UUID.randomUUID().toString()+ substring;

        try {
            file.transferTo(new File(fileLocation+newFile));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFile;
    }
}
